package study.cv.image.controller;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import study.cv.image.mapper.wksheetpdfimg.WkSheetPdfImgEO;
import study.cv.image.mapper.wksheetpdfimg.WkSheetPdfImgMapper;
import study.cv.image.support.utils.SvgUtils;
import study.eggs.result.Result;
import study.eggs.result.Results;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

/**
 * svg 图形
 */
@Slf4j
@RestController
public class SvgController {

    private String t = "https://test.youneng.com/FileCenter/";

    @Autowired
    private WkSheetPdfImgMapper wkSheetPdfImgMapper;

    @PostMapping("/png2Svg")
    public Result png2Svg() {
        //
        PageHelper.startPage(1, 10);
        List<WkSheetPdfImgEO> imgEOLt = wkSheetPdfImgMapper.getPdfImgLt();
        PageInfo<WkSheetPdfImgEO> pageInfo = new PageInfo(imgEOLt);

        //
        pageInfo.getList().forEach(e -> {
            String path = e.getFilePath();
            log.info(">>>>>> {}", t + path);

            String svgName = StrUtil.subAfter(path, "/", true);
            svgName = StrUtil.subBefore(svgName, ".", false);

            StopWatch stopWatch = StopWatch.create("");
            //
            URI uri = URLUtil.toURI(t + path);
            stopWatch.start(">>>>>> 下载 <<<<<<");
            try (InputStream in = URLUtil.getStream(uri.toURL())) {
                BufferedImage img = ImageIO.read(in);
                stopWatch.stop();

                int w = img.getWidth(), h = img.getHeight();
                log.info(">>>>>> type={},  w= {}, h= {}", img.getType(), img.getWidth(), img.getHeight());

                //
                stopWatch.start(">>>>>> 转换 <<<<<<");
                SvgUtils.png2Svg(img, w, h, svgName);
                stopWatch.stop();

                log.info(">>>>>> {} ms", stopWatch.getTotalTimeMillis());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });

        return Results.ok();
    }
}
